Vue Router 4–Scroll Behavior |
您所在的位置:网站首页 › vue router 4 › Vue Router 4–Scroll Behavior |
Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62 Subscribe to my email list now at http://jauyeung.net/subscribe/ Vue Router 4 is in beta and it’s subject to change. To build a single page app easily, we got to add routing so that URLs will be mapped to components that are rendered. In this article, we’ll look at how to use Vue Router 4 with Vue 3. Scroll BehaviorWe can change the scroll behavior with the Vue Router. To do that, we add the scrollBehavior method to the object that we pass into the createRouter method. For example, we can write: Appfoo bar const Foo = { template: `{{n}} ` }; const Bar = { template: "bar" }; const routes = [ { path: "/foo", component: Foo }, { path: "/bar", component: Bar } ]; const router = VueRouter.createRouter({ history: VueRouter.createWebHistory(), routes, scrollBehavior(to, from, savedPosition) { return { left: 0, top: 500 }; } }); const app = Vue.createApp({}); app.use(router); app.mount("#app"); Enter fullscreen mode Exit fullscreen modeWe return an object with the left and top properties. left is the x coordinate and top is the y coordinate we want to scroll to when the route changes. to has the route object of the route we’re moving to. And from has the route object we’re moving from. Now when we click on the router links, we move to somewhere near the top of the page. savedPosition has the position that we scrolled in the previous route. We can use the savedPosition object as follows: Appfoo bar const Foo = { template: `{{n}} ` }; const Bar = { template: `{{n}} ` }; const routes = [ { path: "/foo", component: Foo }, { path: "/bar", component: Bar } ]; const router = VueRouter.createRouter({ history: VueRouter.createWebHistory(), routes, scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition; } else { return { left: 0, top: 0 }; } } }); const app = Vue.createApp({}); app.use(router); app.mount("#app"); Enter fullscreen mode Exit fullscreen modeWhen the savedPosition object is defined, we return it. Otherwise, we scroll to the top when we click on the router links. Now when we scroll to the links, we’ll stay at the bottom of the page. ConclusionWe can scroll to a given position on the page with Vue Router 4 with the scrollBehavior method. |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |